package com.siyoumi.app.modules.accsuper_admin.admin;

import com.siyoumi.app.modules.accsuper_admin.vo.SysAccsuperZzzAppVo;
import com.siyoumi.controller.AdminApiController;
import com.siyoumi.entity.*;
import com.siyoumi.exception.EnumSys;
import com.siyoumi.service.SysAccsuperConfigService;
import com.siyoumi.service.SysAccsuperZzzAppService;
import com.siyoumi.util.XReturn;
import com.siyoumi.util.XStr;
import com.siyoumi.validator.XValidator;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/xadmin/accsuper_admin/accsuper_admin__app__edit")
public class accsuper_admin__app__edit
        extends AdminApiController {
    @GetMapping()
    public XReturn index() {
        SysAccsuperConfigService app = SysAccsuperConfigService.getBean();
        SysAccsuperConfig entityXConfig = app.loadEntity(getPid());
        if (entityXConfig == null) {
            return EnumSys.ERR_VAL.getR("PID异常");
        }

        setPageTitle(XStr.concat(entityXConfig.getKey(), "添加应用"));

        Map<String, Object> data = new HashMap<>();
        data.put("acczapp_x_id", entityXConfig.getKey());
        data.put("app_ids", new ArrayList<>());
        if (isAdminEdit()) {
        }
        getR().setData("data", data);

        SysAccsuperZzzAppService appAcczapp = SysAccsuperZzzAppService.getBean();
        List<SysApp> listApps = appAcczapp.listApps(entityXConfig);
        setPageInfo("list_app", listApps);

        return getR();
    }


    @Transactional
    @PostMapping("/save")
    public XReturn save(@Validated() SysAccsuperZzzAppVo entity, BindingResult result) {
        //统一验证
        XValidator.getResult(result);

        String[] listAppIds = entity.getApp_ids().split(",");
        //
        List<SysAccsuperZzzApp> list = Arrays.stream(listAppIds).map(appId -> {
            SysAccsuperZzzApp entityAcczapp = new SysAccsuperZzzApp();
            entityAcczapp.setAcczapp_app_id(appId);
            entityAcczapp.setAcczapp_x_id(entity.getAcczapp_x_id());
            return entityAcczapp;
        }).collect(Collectors.toList());
        //批量添加
        SysAccsuperZzzAppService.getBean().saveBatch(list);

        return getR();
    }
}
